/// <reference path="../../wx/ad/WxBannerAd.ts" />
namespace mgp.ads {
    export class XmBannerAd extends WxBannerAd {

        protected _bannerAd: any;
        protected _readyShowBanner = false;// banner加载完毕后，才能显示
        protected _bannerLoaded = false;// banner加载完毕后，才能显示
        protected _isHiding = false;

        setInfo(info: IBannerInfo) {
            this._info = info;
            // vivo的banner无法复用,要注意
            this._info.hideIsDestroy = true;
        }

        showBannerAd(justShowByLongPhone?: boolean) {
            if (adModule.state == AdState.NoAd) {
                debugLog('广告状态设置为了未上线状态，所以不显示')
                return;
            }
            if (!this._info || !this._info.ids.length) {
                debugWarn('未设置banner数据')
                return;
            }
            if (justShowByLongPhone && !this._isLongPhone()) {
                // 如果只在长屏幕手机显示banner，且当前手机是短屏幕，则隐藏banner
                if (this._bannerShowing) {
                    this.hideBannerAd();
                }
                return;
            }
            this._justShowByLongPhone = justShowByLongPhone;
            if (this._bannerShowing) return;
            this._bannerAd = this._getBannerAd();

            this._readyShowBanner = true;
            if (this._bannerLoaded) {
                this._bannerShow()
            }
        }

        protected _bannerShow() {
            this._bannerAd.show().then(() => {
                debugLog("banner广告展示成功");
                if (!!this._info.shown) this._info.shown();
                this._bannerShowing = true;
                this._readyShowBanner = false;
            }).catch(err => {
                debugLog("banner广告展示失败", err);
            });
        }

        hideBannerAd(destroy?: boolean) {
            if (!this._info || !this._info.ids || !this._info.ids.length) {
                debugWarn('未设置banner数据')
                return;
            }
            if (!this._bannerAd) return;
            if (!this._bannerShowing || !this._bannerLoaded) return;// 没有显示出广告的时候，或者还没拉取完的时候，不能hide
            if (this._isHiding) return;

            this._isHiding = true;
            this._bannerHide(destroy);
        }

        protected _bannerHide(destroy?: boolean) {

            this._bannerAd.hide().then(() => {
                debugLog("banner广告隐藏成功");
                this._isHiding = false;
                this._bannerShowing = false;
                this._bannerLoaded = false;
                this._readyShowBanner = false;
                this._crtResize = null
                if (destroy || this._info.hideIsDestroy) {
                    this._destroy();
                }
            }).catch(err => {
                debugLog("banner广告隐藏失败", err);
                timerOnce(500, this, () => {
                    // 可以容忍在某些地方不显示banner，但是不能容忍在不该显示banner的地方不隐藏banner
                    this._bannerHide(destroy);
                })
            });
        }

        protected _destroy() {
            if (!this._bannerAd) return;
            this._bannerRemoveListener()
            this._bannerAd.destroy().then(() => {
                debugLog("banner广告销毁成功");
            }).catch(err => {
                debugLog("banner广告销毁失败", err);
            });
            this._bannerAd = null;
        }

        protected _onBannerErr(err) {
            super._onBannerErr(err);
            if (err.errCode == 30009) {
                //createBannerAd 调用频率过高
                this._bannerShowing = false;
                this._bannerLoaded = false;
                this._readyShowBanner = false;
                if (this._bannerAd) {
                    this._bannerAd.destroy().then(() => {
                        debugLog("banner广告销毁成功");
                    }).catch(err => {
                        debugLog("banner广告销毁失败", err);
                    });
                    this._bannerAd = null;
                }
            }
        }
        protected _getBannerAd(id?: string) {
            if (!this._bannerAd) {
                // 没有style字段，banner会在上边显示
                this._bannerAd = this._createBanner(id);
                if (this._bannerAd['javaObjectId'] < 0) {
                    return null;
                }
                this._bannerAddListener()
                if (this._info.aliveTime > 0) {
                    this._timeKey = timerOnce(this._info.aliveTime * 1000, this, this._aliveTimeUp, [], true, this._timeKey)
                }
            }
            return this._bannerAd;
        }

        protected _createBanner(id?: string): any {
            let idx = Math.floor(Math.random() * this._info.ids.length);
            return qg.createBannerAd({
                adUnitId: id || this._info.ids[idx],
                style: this._getDefStyle()
            });
        }
        protected _bannerAddListener() {
            if (!this._bannerAd) return;
            this._bannerAd.onError(this._onBannerErr.bind(this))
            this._bannerAd.onLoad(this._onBannerLoaded.bind(this))
            this._bannerAd.onSize(this._onBannerResize.bind(this))
        }

        protected _bannerRemoveListener() {
            if (!this._bannerAd) return;
            this._bannerAd.offSize(this._onBannerResize.bind(this))
            this._bannerAd.offError(this._onBannerErr.bind(this))
            this._bannerAd.offLoad(this._onBannerLoaded.bind(this))
        }
        protected _getDefStyle(width?: number, height?: number) {
            return {};//style内无需设置任何字段，banner会在屏幕底部居中显示，
        }
        protected _onBannerResize(res) {
            if (!this._bannerAd) return;
            debugLog('banner resize', res)
            if (!!this._crtResize) {
                let { left, top } = this._crtResize(res);
                this._bannerAd.style.left = left;
                this._bannerAd.style.top = top;
            } else if (!!this._info.resize) {
                let { left, top } = this._info.resize(res);
                this._bannerAd.style.left = left;
                this._bannerAd.style.top = top;
            }
        }
        protected _onBannerLoaded(res) {
            super._onBannerLoaded(res);
            this._bannerLoaded = true;
            debugLog('准备中？', this._readyShowBanner)
            if (this._readyShowBanner) {
                this._bannerShow();
            }
        }

    }
}